﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Sprout.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Sprout.Schedule.Web.Models;
using Sprout.Schedule.Web.Options;
using Sprout.Core.Security;
using Sprout.Core.Extensions;
using Sprout.Schedule.Web.Exceptions;
using Sprout.Schedule.Web.Utils;

namespace Sprout.Schedule.Web.Controllers
{
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginController : BaseController
    {
        #region 视图

        [AllowAnonymous]
        [ApiExplorerSettings(IgnoreApi = true)]
        public async Task<IActionResult> Login()
        {
            return View();
        }
        #endregion

        #region 接口

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<LoginDto> Login(LoginModel inputDto)
        {
            var appSettingOption = ServiceLocator.GetOption<AppSettingOption>();
            if (inputDto.LoginName == appSettingOption.LoginName && inputDto.LoginPwd == appSettingOption.LoginPassword)
            {
                LoginUserDto loginUser = new LoginUserDto()
                {
                    UserId = 1,
                    UserName = "管理员"
                };
                var token = AESHelper.Encrypt(loginUser.ToJsonString(), appSettingOption.LoginSecurityKey);
                LoginDto result = new LoginDto()
                {
                    Token = token
                };
                LoginHelper.SetCurrent(token);
                return result;
            }
            else
            {
                throw new WException("账号密码不正确");
            }
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        [HttpPost]
        public void LoginOut()
        {
            LoginHelper.RemoveCurrent();
        }

        #endregion
    }
}